﻿using System;
using System.IO;
using UnityEngine;
using YooAsset;


/// <summary>
/// 文件偏移加密方式
/// </summary>
public class SimpleFileOffsetEncryption : IEncryptionServices
{
    public EncryptResult Encrypt(EncryptFileInfo fileInfo)
    {
        // 说明：对TestRes3资源目录进行加密
        if (fileInfo.BundleName.EndsWith(".bundle"))
        {
            const int offset = 32;
            var fileData = File.ReadAllBytes(fileInfo.FileLoadPath);
            var encryptedData = new byte[fileData.Length + offset];
            Buffer.BlockCopy(fileData, 0, encryptedData, offset, fileData.Length);

            var result = new EncryptResult
            {
                Encrypted = true,
                EncryptedData = encryptedData
            };
            return result;
        }
        else
        {
            var result = new EncryptResult
            {
                Encrypted = false
            };
            return result;
        }
    }
}

/// <summary>
/// 资源文件偏移解密类
/// </summary>
public class SimpleFileOffsetDecryption : IDecryptionServices
{
    /// <summary>
    /// 同步方式获取解密的资源包对象
    /// 注意：加载流对象在资源包对象释放的时候会自动释放
    /// </summary>
    public DecryptResult LoadAssetBundle(DecryptFileInfo fileInfo)
    {
        var decryptResult = new DecryptResult
        {
            ManagedStream = null,
            Result = AssetBundle.LoadFromFile(fileInfo.FileLoadPath, fileInfo.FileLoadCRC, GetFileOffset())
        };
        return decryptResult;
    }

    /// <summary>
    /// 异步方式获取解密的资源包对象
    /// 注意：加载流对象在资源包对象释放的时候会自动释放
    /// </summary>
    public DecryptResult LoadAssetBundleAsync(DecryptFileInfo fileInfo)
    {
        var decryptResult = new DecryptResult
        {
            ManagedStream = null,
            CreateRequest = AssetBundle.LoadFromFileAsync(fileInfo.FileLoadPath, fileInfo.FileLoadCRC, GetFileOffset())
        };
        return decryptResult;
    }

    /// <summary>
    /// 后备方式获取解密的资源包对象
    /// </summary>
    public DecryptResult LoadAssetBundleFallback(DecryptFileInfo fileInfo)
    {
        return new DecryptResult();
    }

    /// <summary>
    /// 获取解密的字节数据
    /// </summary>
    public byte[] ReadFileData(DecryptFileInfo fileInfo)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 获取解密的文本数据
    /// </summary>
    public string ReadFileText(DecryptFileInfo fileInfo)
    {
        throw new NotImplementedException();
    }

    private static ulong GetFileOffset()
    {
        return 32;
    }
}